package site.wetsion.galio.auth.filter;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import site.wetsion.galio.data.service.UserService;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author weixin
 * @version 1.0
 * @CLassName AuthorizeFilter
 * @date 2019/3/19 6:45 PM
 */
public class AuthorizeFilter extends AbstractAuthenticationProcessingFilter {

    private UserService userService;

    public AuthorizeFilter(String defaultFilterProcessesUrl,
                           AuthenticationManager authenticationManager,
                           UserService userService) {
        super(defaultFilterProcessesUrl);
        setAuthenticationManager(authenticationManager);
        this.userService = userService;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        Authentication at = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(at)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            AuthenticationManager authenticationManager = getAuthenticationManager();
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return authentication;
        } else {
            return at;
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
}
